import Common from '../../../../common/common.js';
let common = new Common;
const app = getApp();
Page({
  data: {
    isSpecial: 0,//是否是特殊名片样式
    orgSeq: '',
    userId: '',
    stroeInfo: {},
    userInfo: {},
    user: '',
    styleList: [],//店铺风格列表
    id: null,
    // canvas 定义
    width: 355,
    height: 208,
    shopCard: '', //店铺名片
    imgUrl: common.imgUrl,
    isDisable: false,//防止多次点击
    background: '',
    ecode: "",
    doorwayPic: '',
    fontColor: '',//文字颜色
  },
  // 查询店铺名片风格
  queryStoreUsableCard: function (e) {
    let data = {
      orgSeq: this.data.orgSeq
    }
    common.requestAjax('/api/user-service/v1/StoreCard/queryStoreUsableCard', 'get', data).then(res => {
      console.log(res)
      for (var i = 0; i < res.data.records.length; i++) {
        if (res.data.records[i].checked == 1) {
          this.setData({
            id: res.data.records[i].uuid,
            background: res.data.records[i].cardPic,
            fontColor: res.data.records[i].fontColor,
            isSpecial: Number(res.data.records[i].isSpecial) || 0
          })
        }
      }
      console.log(this.data.id, '选中的id')
      this.setData({
        styleList: res.data.records,
      })

    }).catch(err => {
      console.log(err);
    })
  },
  // 保存风格
  submit: function (e) {
    this.updateStoreCardConfig()
  },
  // 保存至相册
  canvasKapian() {
    wx.getSetting({
      success: res => {
        console.log(res);
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: res => {
              if (this.data.isSpecial) {
                //特殊名片
                this.canvasClick1();
              } else {
                this.canvasClick();
              }
            },
            fail: err => {
              wx.showModal({
                title: "提示",
                content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
                success: res => {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          if (this.data.isSpecial) {
                            //特殊名片
                            this.canvasClick1();
                          } else {
                            this.canvasClick();
                          }

                        } else {
                          wx.showToast({
                            title: '获取权限失败,无法使用保存图片或视频到您的相册',
                            icon: 'none'
                          })
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        } else {
          if (this.data.isSpecial) {
            //特殊名片
            this.canvasClick1();
          } else {
            this.canvasClick();
          }
        }
      }
    })
  },
  canvasClick() {
    this.setData({
      isDisable: true
    })
    wx.showLoading({
      title: '名片生成中...',
    })
    let headPicUrl = this.data.doorwayPic.replace(":443", '');
    let background = this.data.background.replace(":443", '') || this.data.imgUrl + 'shopimg/minebg.png';//背景图  
    let image1 = this.localImge(background);
    let image2 = this.localImge(this.data.wxCode);
    let image3 = this.localImge(headPicUrl)
    Promise.all([image1, image2, image3]).then(res => {
      console.log(res);
      let background1 = res[0];
      let ecode1 = res[1];
      let headPicUrl1 = res[2]
      let top = 20;
      let left = 20;
      const ctx = wx.createCanvasContext("businessCard");
      // 画布背景色
      ctx.setFillStyle("#ffffff");
      //画布大小 
      ctx.fillRect(0, 0, this.data.width, this.data.height);
      // 背景图
      ctx.drawImage(background1, 0, 0, this.data.width, this.data.height);
      // logo
      ctx.drawImage('../../../../images/index/logo.png', 20, 20, 43, 32);

      ctx.fillStyle = this.data.fontColor || '#ffe5ca';
      // 店铺名字
      ctx.setFontSize(15);
      // ctx.fillStyle="";
      ctx.fillText(this.data.stroeInfo.storeName || '', 83, 40);
      // 专卖店
      ctx.setFontSize(10);
      this.drawText(ctx, this.data.stroeInfo.storeDesc || "", 83, 58, 389, 180)
      // 二维码
      this.circleImg(ctx, ecode1, 280, top, 20, 20)
      // 头像图片
      this.circleImg(ctx, headPicUrl1 || '../../images/logo/logo1.png', 10, 110, 25, 25)
      // 名字 店主||店长||店员
      ctx.setFontSize(18);
      let member = ''
      if (this.data.userInfo.userType == 4) {
        member = '店主'
      } else if (this.data.userInfo.userType == 5) {
        member = '店长'
      } else if (this.data.userInfo.userType == 6) {
        member = '店员'
      }
      ctx.fillText(this.data.userInfo.realName + ' ' + member, 83, 126);
      // 电话图标
      ctx.drawImage('../../../../images/icon/tel1.png', 83, 138, 10, 10);
      // 电话号码
      ctx.setFontSize(11);
      ctx.fillText(this.data.userInfo.tel || '', 100, 148);
      // 地址图标
      ctx.drawImage('../../../../images/icon/adress.png', 83, 156, 10, 10);
      // 详细地址
      ctx.setFontSize(11);
      ctx.fillText(this.data.stroeInfo.storeAddressDetail || '', 100, 166);
      ctx.save();
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: "businessCard",
          success: res => {
            wx.hideLoading();
            this.setData({
              shopCard: res.tempFilePath
            });
            console.log("成功" + this.data.shopCard)
            this.downFn();
          },
          fail: err => {
            console.log('生成失败', err);
          }
        });
      });

    }).catch(err => {
      console.log(err);
      wx.hideLoading();
      wx.showToast({
        title: '图片加载失败,请返回重试',
        icon: 'none'
      })
    })
  },
  //生成本地图片
  localImge: function (src) {
    console.log('src', src);
    return new Promise(function (resolve, reject) {
      wx.downloadFile({
        url: src,
        success: function (res) {
          resolve(res.tempFilePath);
        },
        fail: err => {
          reject(err)
        }
      });
    });
  },
  //保存图片
  downFn() {
    let imgurl = '';
    wx.showLoading({
      title: '保存中...',
    })
    imgurl = this.data.shopCard;
    wx.saveImageToPhotosAlbum({
      filePath: imgurl,
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: "保存成功，从相册中分享到朋友圈吧",
          icon: "none",
          duration: 4000
        });
        this.setData({
          isDisable: false
        })
        // this.updateStoreCardConfig()
        this.addNum();   //统计次数
      },
      fail: function (err) {
        console.log(err)
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.hideLoading();
          wx.showModal({
            title: "提示",
            content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  complete: (res) => {
                    console.log(res);
                  },
                })
              }
            }
          })
        }
      }
    });
  },
  // 圆形图片
  circleImg: function (ctx, img, x, y, r) {
    ctx.save()
    ctx.beginPath()
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore()
  },
  // 超出换行
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 16; //16为字体的高度防止文字重叠
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },
  //  点击选择风格
  changeStyle: function (e) {
    console.log(e)
    let { uuid, cardPic, fontColor, isSpecial } = e.currentTarget.dataset.item;
    this.setData({
      id: uuid,
      background: cardPic,
      fontColor,
      isSpecial:Number(isSpecial)
    })
  },

  getInfo: function (e) {
    let data = {
      userId: this.data.userId,
      orgSeq: this.data.orgSeq
    }
    common.requestAjax('/api/user-service/v1/foreign/getUserAndStoreInfo', 'GET', data).then(res => {
      this.setData({
        stroeInfo: res.data.storeInfoDTO,
        userInfo: res.data.userInfoDTO,
      })
      this.getWxCode()//获取小程序码
    }).catch(err => {
      console.log(err);
    })
  },
  // 更新背景图
  updateStoreCardConfig: function (e) {
    wx.showLoading({
      title: '正在更换中。。。'
    })
    let data = {
      orgSeq: this.data.orgSeq,//app.globalData.orgSeq,
      userId: app.globalData.userId,
      cardId: this.data.id
    }
    common.requestAjax('/api/user-service/v1/StoreCard/updateStoreCardConfig', 'post', data).then(res => {
      wx.hideLoading({})
      wx.showToast({
        title: '店铺风格更换成功',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack({})
      }, 2000);
    }).catch(err => {
      console.log(err);
    })
  },
  // 添加添加次数
  addNum: function () {
    //type 1 活动名片 2商品名片 3店铺名片
    common.requestAjax('/api/user-service/v1/storeDownloadCount/addCardAmount?orgSeq=' + getApp().globalData.shopInfo.orgSeq + '&type=' + 3, 'POST').then(res => {
    }).catch(err => {
      console.log(err);
    })
  },
  // 获得小程序码
  getWxCode() {
    let data = {
      type: 3,//1活动分享   2商品分享  3 店铺分享
      page: "pages/shop/index",
      //活动type==3 店铺type==4
      sceneStr: getApp().globalData.userId + ',' + getApp().globalData.shopInfo.orgSeq + ',' + 4,
      appid: getApp().globalData.appId,
      secret: getApp().globalData.wx_code,
      width: 300,
      orgSeq: this.data.orgSeq,//getApp().globalData.shopInfo.orgSeq,
      userId: this.data.userId,//getApp().globalData.userId,
      phone: this.data.userInfo.tel
    }
    common.requestAjax('/api/file-service/v1/share/appletCode', 'POST', data).then(res => {
      if (res.data.code) {
        let wxCode = res.data.url.replace(":443", '');
        this.setData({
          wxCode,
        })
      }
    }).catch(err => {
      console.log(err);
    })
  },
  prewImage() {
    wx.previewImage({
      urls: [this.data.wxCode],
      complete: (res) => { },
      current: this.data.wxCode,
      fail: (res) => { },
      success: (res) => { },
    })
  },
  onLoad: function (options) {
    let orgSeq = app.globalData.orgSeq;
    let userId = app.globalData.userId;
    this.setData({
      orgSeq: orgSeq,
      userId: userId,
      user: app.globalData.shopInfo.userType,
      doorwayPic: options.doorwayPic,
    })
    console.log(options.doorwayPic)
  },
  onShow: function () {
    this.getInfo();
    this.queryStoreUsableCard();
  },
  //特殊名片生成
  canvasClick1() {
    this.setData({
      isDisable: true
    })

    wx.showLoading({
      title: '名片生成中...',
    })
    let { storeName, storeDesc, storeAddressDetail } = this.data.stroeInfo;
    let { userType, realName, tel } = this.data.userInfo;

    let background = this.data.background.replace(":443", '') || this.data.imgUrl + 'shopimg/minebg.png';//背景图  
    let image1 = this.localImge(background);
    let image2 = this.localImge(this.data.wxCode);

    Promise.all([image1, image2]).then(res => {
      console.log(res);
      let background1 = res[0];
      let ecode1 = res[1];
      const ctx = wx.createCanvasContext("businessCard");
      // 画布背景色
      ctx.setFillStyle("#ffffff");
      //画布大小 
      ctx.fillRect(0, 0, this.data.width, this.data.height);
      // 背景图
      ctx.drawImage(background1, 0, 0, this.data.width, this.data.height);

      ctx.font = 'normal bold 14px sans-serif';
      ctx.fillStyle = this.data.fontColor || '#ffe5ca';


      // 店铺名字
      //ctx.fillText(this.data.stroeInfo.storeName || '', 110, 35);
      this.drawText(ctx, storeName || '', 110, 35, 389, 180)

      ctx.font = 'normal 12px sans-serif';
      //判断门店的字数是否要换行
      if (storeName.length > 12) {
        // 专卖店
        this.drawText(ctx, storeDesc || "", 110, 69, 389, 180)
      } else {
        // 专卖店
        this.drawText(ctx, storeDesc || "", 110, 52, 389, 180)
      }

      // 二维码
      this.circleImg(ctx, ecode1, 280, 15, 30, 30);

      //店员名字
      realName = realName.slice(0, 1) + ' ' + realName.slice(1);
      ctx.font = 'normal bold 25px sans-serif';
      ctx.fillText(realName, 10, 130);

      //身份
      let member = ''
      if (userType == 4) {
        member = '店主'
      } else if (userType == 5) {
        member = '店长'
      } else if (userType == 6) {
        member = '店员'
      }
      ctx.font = 'normal 14px sans-serif';
      ctx.fillText('/' + member, realName.length * 25, 130);

      //手机号
      ctx.font = 'normal 12px sans-serif';
      ctx.fillText('Mob:' + tel, 10, 155);

      // 详细地址
      ctx.fillText('Add:', 10, 170);
      this.drawText(ctx, storeAddressDetail, 35, 170, 389, 130)

      ctx.save();
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: "businessCard",
          success: res => {
            wx.hideLoading();
            this.setData({
              shopCard: res.tempFilePath
            });
            console.log("成功" + this.data.shopCard)
            this.downFn();
          },
          fail: err => {
            console.log('生成失败', err);
          }
        });
      });

    }).catch(err => {
      console.log(err);
      wx.hideLoading();
      wx.showToast({
        title: '图片加载失败,请返回重试',
        icon: 'none'
      })
    })
  },
})